<template>
  <div class="p-2">
    <el-card shadow="never">
      <!-- 搜索表单 -->
      <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="100px">
        <el-form-item label="订单编号" prop="orderNo">
          <el-input
            v-model="queryParams.orderNo"
            placeholder="请输入订单编号"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="期数" prop="periodNo">
          <el-input-number
            v-model="queryParams.periodNo"
            :min="1"
            placeholder="请输入期数"
            controls-position="right"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="还款状态" prop="repaymentStatus">
          <el-select v-model="queryParams.repaymentStatus" placeholder="请选择还款状态" clearable style="width: 200px">
            <el-option v-for="dict in beauty_repayment_status" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="还款日期" style="width: 340px">
          <el-date-picker
            v-model="repaymentDateRange"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 工具栏 -->
      <el-row :gutter="10" class="mb-4">
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="Money"
            :disabled="multiple"
            @click="handleBatchDeduct"
            v-hasPermi="['beauty:repayment:deduct']"
          >批量扣款</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['beauty:repayment:export']"
          >导出</el-button>
        </el-col>
      </el-row>

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="repaymentList"
        @selection-change="handleSelectionChange"
        :row-class-name="tableRowClassName"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="计划ID" align="center" prop="planId" width="100" />
        <el-table-column label="订单ID" align="center" prop="orderId" width="100" />
        <el-table-column label="订单编号" align="center" prop="orderNo" width="180" show-overflow-tooltip />
        <el-table-column label="期数" align="center" prop="periodNo" width="80" />
        <el-table-column label="应还金额" align="center" prop="repaymentAmount" width="120">
          <template #default="scope">
            <span :class="{ 'text-red-500': scope.row.repaymentStatus === '3' }">
              {{ formatCurrency(scope.row.repaymentAmount) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="本金" align="center" prop="principal" width="120">
          <template #default="scope">
            <span :class="{ 'text-red-500': scope.row.repaymentStatus === '3' }">
              {{ formatCurrency(scope.row.principal) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="利息" align="center" prop="interest" width="120">
          <template #default="scope">
            <span :class="{ 'text-red-500': scope.row.repaymentStatus === '3' }">
              {{ formatCurrency(scope.row.interest) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="应还日期" align="center" prop="repaymentDate" width="120" />
        <el-table-column label="实际还款时间" align="center" prop="actualRepaymentTime" width="160" />
        <el-table-column label="还款状态" align="center" prop="repaymentStatus" width="100">
          <template #default="scope">
            <dict-tag :options="beauty_repayment_status" :value="scope.row.repaymentStatus" />
          </template>
        </el-table-column>
        <el-table-column label="逾期天数" align="center" prop="overdueDays" width="100">
          <template #default="scope">
            <span v-if="scope.row.overdueDays > 0" class="text-red-500 font-bold">
              {{ scope.row.overdueDays }}
            </span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="逾期金额" align="center" prop="overdueAmount" width="120">
          <template #default="scope">
            <span v-if="scope.row.overdueAmount > 0" class="text-red-500 font-bold">
              {{ formatCurrency(scope.row.overdueAmount) }}
            </span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="300">
          <template #default="scope">
            <el-button
              link
              type="primary"
              icon="View"
              @click="handleDetail(scope.row)"
              v-hasPermi="['beauty:repayment:query']"
            >详情</el-button>
            <el-button
              v-if="scope.row.repaymentStatus !== '2'"
              link
              type="success"
              icon="Money"
              @click="handleManualDeduct(scope.row)"
              v-hasPermi="['beauty:repayment:deduct']"
            >手动扣款</el-button>
            <el-button
              v-if="scope.row.repaymentStatus !== '2'"
              link
              type="warning"
              icon="Bell"
              @click="handleRemind(scope.row)"
              v-hasPermi="['beauty:repayment:remind']"
            >催收</el-button>
            <el-button
              v-if="scope.row.overdueDays > 0 && scope.row.overdueAmount > 0"
              link
              type="danger"
              icon="Delete"
              @click="handleWaiveOverdueFee(scope.row)"
              v-hasPermi="['beauty:repayment:waive']"
            >减免逾期费</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog title="还款计划详情" v-model="detailDialog.visible" width="800px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="计划ID">{{ detailDialog.data.planId }}</el-descriptions-item>
        <el-descriptions-item label="订单ID">{{ detailDialog.data.orderId }}</el-descriptions-item>
        <el-descriptions-item label="订单编号" :span="2">{{ detailDialog.data.orderNo }}</el-descriptions-item>
        <el-descriptions-item label="期数">{{ detailDialog.data.periodNo }}</el-descriptions-item>
        <el-descriptions-item label="应还金额">
          <span :class="{ 'text-red-500': detailDialog.data.repaymentStatus === '3' }">
            {{ formatCurrency(detailDialog.data.repaymentAmount) }}
          </span>
        </el-descriptions-item>
        <el-descriptions-item label="本金">
          <span :class="{ 'text-red-500': detailDialog.data.repaymentStatus === '3' }">
            {{ formatCurrency(detailDialog.data.principal) }}
          </span>
        </el-descriptions-item>
        <el-descriptions-item label="利息">
          <span :class="{ 'text-red-500': detailDialog.data.repaymentStatus === '3' }">
            {{ formatCurrency(detailDialog.data.interest) }}
          </span>
        </el-descriptions-item>
        <el-descriptions-item label="应还日期">{{ detailDialog.data.repaymentDate }}</el-descriptions-item>
        <el-descriptions-item label="实际还款时间">{{ detailDialog.data.actualRepaymentTime || '-' }}</el-descriptions-item>
        <el-descriptions-item label="还款状态">
          <dict-tag :options="beauty_repayment_status" :value="detailDialog.data.repaymentStatus" />
        </el-descriptions-item>
        <el-descriptions-item label="逾期天数">
          <span v-if="detailDialog.data.overdueDays > 0" class="text-red-500 font-bold">
            {{ detailDialog.data.overdueDays }} 天
          </span>
          <span v-else>-</span>
        </el-descriptions-item>
        <el-descriptions-item label="逾期金额">
          <span v-if="detailDialog.data.overdueAmount > 0" class="text-red-500 font-bold">
            {{ formatCurrency(detailDialog.data.overdueAmount) }}
          </span>
          <span v-else>-</span>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ detailDialog.data.createTime }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialog.visible = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 手动扣款对话框 -->
    <el-dialog title="手动扣款" v-model="deductDialog.visible" width="500px" append-to-body>
      <el-descriptions :column="1" border>
        <el-descriptions-item label="订单编号">{{ deductDialog.data.orderNo }}</el-descriptions-item>
        <el-descriptions-item label="期数">第 {{ deductDialog.data.periodNo }} 期</el-descriptions-item>
        <el-descriptions-item label="应还金额">
          <span class="text-red-500 font-bold">{{ formatCurrency(deductDialog.data.repaymentAmount) }}</span>
        </el-descriptions-item>
      </el-descriptions>
      <el-alert
        title="确认要对该还款计划进行手动扣款吗？"
        type="warning"
        :closable="false"
        class="mt-4"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="deductDialog.visible = false">取 消</el-button>
          <el-button type="primary" @click="confirmManualDeduct" :loading="deductDialog.loading">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 催收对话框 -->
    <el-dialog title="催收提醒" v-model="remindDialog.visible" width="600px" append-to-body>
      <el-form ref="remindFormRef" :model="remindForm" :rules="remindRules" label-width="120px">
        <el-descriptions :column="1" border class="mb-4">
          <el-descriptions-item label="订单编号">{{ remindDialog.data.orderNo }}</el-descriptions-item>
          <el-descriptions-item label="期数">第 {{ remindDialog.data.periodNo }} 期</el-descriptions-item>
          <el-descriptions-item label="应还金额">
            <span class="text-red-500 font-bold">{{ formatCurrency(remindDialog.data.repaymentAmount) }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="应还日期">{{ remindDialog.data.repaymentDate }}</el-descriptions-item>
          <el-descriptions-item label="逾期天数" v-if="remindDialog.data.overdueDays > 0">
            <span class="text-red-500 font-bold">{{ remindDialog.data.overdueDays }} 天</span>
          </el-descriptions-item>
        </el-descriptions>
        <el-form-item label="催收信息" prop="remindMessage">
          <el-input
            v-model="remindForm.remindMessage"
            type="textarea"
            :rows="4"
            placeholder="请输入催收信息（可选）"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="remindDialog.visible = false">取 消</el-button>
          <el-button type="primary" @click="confirmRemind" :loading="remindDialog.loading">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 减免逾期费对话框 -->
    <el-dialog title="减免逾期费" v-model="waiveDialog.visible" width="600px" append-to-body>
      <el-form ref="waiveFormRef" :model="waiveForm" :rules="waiveRules" label-width="120px">
        <el-descriptions :column="1" border class="mb-4">
          <el-descriptions-item label="订单编号">{{ waiveDialog.data.orderNo }}</el-descriptions-item>
          <el-descriptions-item label="期数">第 {{ waiveDialog.data.periodNo }} 期</el-descriptions-item>
          <el-descriptions-item label="逾期天数">
            <span class="text-red-500 font-bold">{{ waiveDialog.data.overdueDays }} 天</span>
          </el-descriptions-item>
          <el-descriptions-item label="逾期金额">
            <span class="text-red-500 font-bold">{{ formatCurrency(waiveDialog.data.overdueAmount) }}</span>
          </el-descriptions-item>
        </el-descriptions>
        <el-form-item label="减免金额" prop="waiveAmount">
          <el-input-number
            v-model="waiveForm.waiveAmount"
            :min="0.01"
            :max="waiveDialog.data.overdueAmount"
            :precision="2"
            :step="0.01"
            controls-position="right"
            style="width: 100%"
          />
          <div class="text-gray-500 text-sm mt-1">最多可减免: {{ formatCurrency(waiveDialog.data.overdueAmount) }}</div>
        </el-form-item>
        <el-form-item label="减免原因" prop="waiveReason">
          <el-input
            v-model="waiveForm.waiveReason"
            type="textarea"
            :rows="4"
            placeholder="请输入减免原因"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="waiveDialog.visible = false">取 消</el-button>
          <el-button type="primary" @click="confirmWaive" :loading="waiveDialog.loading">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="BeautyRepayment">
import { ref, reactive, getCurrentInstance } from 'vue';
import type { ComponentInternalInstance } from 'vue';
import { ElForm, ElMessageBox, ElMessage } from 'element-plus';
import {
  listRepayment,
  getRepayment,
  manualDeduct,
  batchManualDeduct,
  remindRepayment,
  waiveOverdueFee,
  exportRepayment
} from '@/api/beauty/repayment';
import type {
  RepaymentQuery,
  RepaymentVO,
  ManualDeductRequest,
  RemindRequest,
  WaiveOverdueFeeRequest
} from '@/api/beauty/repayment';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { beauty_repayment_status } = toRefs<any>(proxy?.useDict('beauty_repayment_status'));

const loading = ref(true);
const ids = ref<number[]>([]);
const multiple = ref(true);
const total = ref(0);
const repaymentList = ref<RepaymentVO[]>([]);
const repaymentDateRange = ref<[string, string]>(['', '']);

const queryFormRef = ref<InstanceType<typeof ElForm>>();
const remindFormRef = ref<InstanceType<typeof ElForm>>();
const waiveFormRef = ref<InstanceType<typeof ElForm>>();

const queryParams = ref<RepaymentQuery>({
  pageNum: 1,
  pageSize: 10,
  orderNo: undefined,
  periodNo: undefined,
  repaymentStatus: undefined,
  beginRepaymentDate: undefined,
  endRepaymentDate: undefined
});

const detailDialog = reactive({
  visible: false,
  data: {} as RepaymentVO
});

const deductDialog = reactive({
  visible: false,
  loading: false,
  data: {} as RepaymentVO
});

const remindDialog = reactive({
  visible: false,
  loading: false,
  data: {} as RepaymentVO
});

const waiveDialog = reactive({
  visible: false,
  loading: false,
  data: {} as RepaymentVO
});

const remindForm = ref<RemindRequest>({
  planId: 0,
  remindMessage: ''
});

const waiveForm = ref<WaiveOverdueFeeRequest>({
  planId: 0,
  waiveAmount: 0,
  waiveReason: ''
});

const remindRules = reactive({
  remindMessage: [
    { max: 500, message: '催收信息不能超过500个字符', trigger: 'blur' }
  ]
});

const waiveRules = reactive({
  waiveAmount: [
    { required: true, message: '减免金额不能为空', trigger: 'blur' }
  ],
  waiveReason: [
    { required: true, message: '减免原因不能为空', trigger: 'blur' },
    { max: 500, message: '减免原因不能超过500个字符', trigger: 'blur' }
  ]
});

// 格式化货币
function formatCurrency(amount: number | undefined): string {
  if (amount === undefined || amount === null) {
    return '¥0.00';
  }
  return '¥' + amount.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
}

// 表格行样式
function tableRowClassName({ row }: { row: RepaymentVO }): string {
  if (row.repaymentStatus === '3') {
    return 'overdue-row';
  }
  return '';
}

// 查询还款计划列表
function getList() {
  loading.value = true;
  // 处理日期范围
  if (repaymentDateRange.value && repaymentDateRange.value.length === 2) {
    queryParams.value.beginRepaymentDate = repaymentDateRange.value[0];
    queryParams.value.endRepaymentDate = repaymentDateRange.value[1];
  } else {
    queryParams.value.beginRepaymentDate = undefined;
    queryParams.value.endRepaymentDate = undefined;
  }

  listRepayment(queryParams.value).then((response: any) => {
    repaymentList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 搜索按钮操作
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

// 重置按钮操作
function resetQuery() {
  repaymentDateRange.value = ['', ''];
  queryFormRef.value?.resetFields();
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection: RepaymentVO[]) {
  ids.value = selection.map(item => item.planId);
  multiple.value = !selection.length;
}

// 详情按钮操作
function handleDetail(row: RepaymentVO) {
  getRepayment(row.planId).then((response: any) => {
    detailDialog.data = response.data;
    detailDialog.visible = true;
  });
}

// 手动扣款按钮操作
function handleManualDeduct(row: RepaymentVO) {
  deductDialog.data = row;
  deductDialog.visible = true;
}

// 确认手动扣款
function confirmManualDeduct() {
  deductDialog.loading = true;
  const data: ManualDeductRequest = {
    planId: deductDialog.data.planId
  };
  manualDeduct(data)
    .then(() => {
      ElMessage.success('手动扣款成功');
      deductDialog.visible = false;
      getList();
    })
    .finally(() => {
      deductDialog.loading = false;
    });
}

// 批量手动扣款
function handleBatchDeduct() {
  if (ids.value.length === 0) {
    ElMessage.warning('请选择要扣款的还款计划');
    return;
  }
  ElMessageBox.confirm('是否确认对选中的还款计划进行批量扣款？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    return batchManualDeduct(ids.value);
  }).then(() => {
    getList();
    ElMessage.success('批量扣款成功');
  });
}

// 催收按钮操作
function handleRemind(row: RepaymentVO) {
  remindDialog.data = row;
  remindForm.value = {
    planId: row.planId,
    remindMessage: ''
  };
  remindDialog.visible = true;
}

// 确认催收
function confirmRemind() {
  remindFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      remindDialog.loading = true;
      remindRepayment(remindForm.value)
        .then(() => {
          ElMessage.success('催收提醒已发送');
          remindDialog.visible = false;
          getList();
        })
        .finally(() => {
          remindDialog.loading = false;
        });
    }
  });
}

// 减免逾期费按钮操作
function handleWaiveOverdueFee(row: RepaymentVO) {
  waiveDialog.data = row;
  waiveForm.value = {
    planId: row.planId,
    waiveAmount: 0,
    waiveReason: ''
  };
  waiveDialog.visible = true;
}

// 确认减免逾期费
function confirmWaive() {
  waiveFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      waiveDialog.loading = true;
      waiveOverdueFee(waiveForm.value)
        .then(() => {
          ElMessage.success('逾期费减免成功');
          waiveDialog.visible = false;
          getList();
        })
        .finally(() => {
          waiveDialog.loading = false;
        });
    }
  });
}

// 导出按钮操作
function handleExport() {
  ElMessageBox.confirm('是否确认导出所有还款计划数据项？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    proxy?.download(
      '/admin/beauty/repayment/export',
      {
        ...queryParams.value
      },
      `repayment_${new Date().getTime()}.xlsx`
    );
  });
}

getList();
</script>

<style scoped>
:deep(.overdue-row) {
  background-color: #fef0f0;
}

.text-red-500 {
  color: #f56c6c;
}

.font-bold {
  font-weight: bold;
}

.text-gray-500 {
  color: #909399;
}

.text-sm {
  font-size: 0.875rem;
}

.mt-1 {
  margin-top: 0.25rem;
}

.mt-4 {
  margin-top: 1rem;
}

.mb-4 {
  margin-bottom: 1rem;
}
</style>
